// 作者:于大明
// 职责：处理业务逻辑
import WXPayOrder from '@/service/02WX/WXPayOrderAppService.js';
import DJViedeoCollection from '@/service/70DJ/DJViedeoCollectionAppService.js';
import wx from "@/lib/weixin-js-sdk/index.js";
let mixin = {
	// 负责程序中需要进行set的数据 就是页面交互需要改的数据 比如点击checkbox 需要设置true false 和存放ajax的输入输出 (尽量少去定义data里面的属性 多用computed或者filters或者组件进行处理) 
	// 1 能不能在页面单行代码实现
	// 2 能不能不用data methods去实现这个功能
	data() {
		let videoLst=[{
					id: "video0",
					videoUrl: '',
					viedeoCollectionPosterUrl: this.videoDataList[0].viedeoCollectionPosterUrl,
					videoItem:this.videoDataList[0]
				},
				{
					id: "video1",
					videoUrl:'',
					viedeoCollectionPosterUrl: this.videoDataList[1].viedeoCollectionPosterUrl,
					videoItem:this.videoDataList[1]
				},
				{
					id: "video2",
					videoUrl: '',
					viedeoCollectionPosterUrl: this.videoDataList[2].viedeoCollectionPosterUrl,
					videoItem:this.videoDataList[2]
				}
			];
		return {
			buyProducts: [
				// {
				// 	id: '990',
				// 	text: '9.9元解锁全集',
				// 	videos: 1000
				// },
				{
					id: '1990',
					text: '<text style="font-weight: bold;font-size: 18px;color: #ff5000;">19.9</text>元解锁全集',
					videos: 1000
				},
				// {
				// 	id: '300',
				// 	text: '3元解锁10集',
				// 	videos: 10
				// },
				{
					id: '390',
					text: '<text style="font-weight: bold;font-size: 18px;color: #ff5000;">3.9</text>元解锁6集',
					videos: 6
				}
			],
			circular: true,
			videoList: videoLst,
			_videoIndex: 0,
			_videoContextList: [],
			_videoDataIndex: 0,

			currentStatus: 'pause', // 播放的状态

			// 订单数据
			orderDatas: [],
			// 短剧数据
			djDatas: [],
			// 查询
			searchText: '',
			spPath:'pages/common/testAd/testAd.html?userId=123'
		};
	},
	// 负责和页面事件进行交互
	methods: {
		spLaunch(e){
			// this.$util.wxCanMove(false);
			// this.$refs.adPopup.close();
		},
		spError(e){
			alert(JSON.stringify(e));
		},
		orderPopupMaskClick(){
			this.$util.wxCanMove(false);
			this.openDj();
		},
		openVideo() {
			this.$refs.viedoPopup.open('bottom');
			this.$util.wxCanMove(true);
		},
		openDj() {
			this.$refs.viedoPopup.close();
			this.$refs.buyPopup.close();
			this.$refs.djPopup.open('bottom');
			this.$util.wxCanMove(true);
		},
		// 
		async getViedeCollections() {
			let res = await DJViedeoCollection.GetViedeCollections({});
			// 判断接口是正常返回 没有报错
			if (res) {
				this.djDatas = res.datas;
			}
		},
		openOrder() {
			this.getMyWxOrders();
			this.$refs.viedoPopup.close();
			this.$refs.orderPopup.open('bottom');
			this.$util.wxCanMove(true);
		},
		async getMyWxOrders() {
			let res = await WXPayOrder.GetMyWxOrders({});
			// 判断接口是正常返回 没有报错
			if (res) {
				this.orderDatas = res.datas;
			}
		},
		async buyProduct(e) {
			this.$refs.buyPopup.close();
			this.$util.wxCanMove(false);
			let {
				index
			} = e.detail;
			const productInfo = this.buyProducts[index];
			const indexVideo = this.videoDataList.findIndex(x => !x.videoUrl);
			if (indexVideo > -1) {
				let jsCountStr = `${indexVideo+1}`;
				if (productInfo.videos > 1) {
					jsCountStr +=
						`~${(indexVideo+productInfo.videos)>this.videoDataList.length?this.videoDataList.length:(indexVideo+productInfo.videos)}`;
				}
				let content = `确认解锁${jsCountStr}集？`;
				const conRes = await this.$cw.showConfirm(content);
				if (conRes) {
					let res = await this.$cw.payOrder(10, productInfo.id, `${productInfo.text}[${jsCountStr}]`,
						this.videoDataList[0].viedeoCollectionGUID);
					if (res) {
						this.$emit('paySuccess');
					}else{
						this.openDj();
						setTimeout(()=>{
							this.$util.wxCanMove(true);
						},50);
					}
				}
				else{
					this.openDj();
				}
			}
		},
		// video结束
		videoEnd() {
			this.onSwiperChange({
				detail: {
					current: 1,
					realIndex: (this._videoDataIndex + 1)
				}
			})
		},
		pauseVideo() {
			let isPause = document.querySelector(`#video${this._videoIndex} > div > video`).paused;
			if(isPause){
				this.playVideo(false);
			}else{
				this.currentStatus = 'pause';
				this._videoContextList[this._videoIndex].pause();
			}
			// if (this.currentStatus == 'pause') {
			// 	this.currentStatus = 'play';
			// 	this.playVideo();
			// } else {
			// 	this.currentStatus = 'pause';
			// 	this._videoContextList[this._videoIndex].pause();
			// }
		},
		playVideo(isNeedAutoJuage=true) {
			setTimeout(() => {
				this.currentStatus = 'play';
				this._videoContextList[this._videoIndex].play();
				// wx.config({
				//     // 配置信息, 即使不正确也能使用 wx.ready
				//     debug: false,
				//     appId: '',
				//     timestamp: 1,
				//     nonceStr: '',
				//     signature: '',
				//     jsApiList: []
				// });
				// wx.ready(()=> {
					
				// });
				if(isNeedAutoJuage){
					setTimeout(() => {
						let isPause = document.querySelector(`#video${this._videoIndex} > div > video`).paused;
						if (isPause) {
							this.currentStatus = 'pause';
						}else{
							this.currentStatus = 'play';
						}
					}, 1000);
				}
				
			}, 200)
		},
		error(e) {
			this._videoContextList[this._videoIndex].pause();
		},
		init() {
			for (var i = 0; i < this.videoList.length; i++) {
				this._videoContextList.push(uni.createVideoContext('video' + i, this));
			}
			this.updateVideo(true);
		},
		onHide() {
			this.currentStatus = 'pause';
			this._videoContextList[this._videoIndex].pause();
		},
		onSwiperChange(e) {
			this._videoContextList.map(x => {
				this.currentStatus = 'pause';
				x.pause();
			});
			this.$refs.viedoPopup.close();
			
			let _videoDataIndex=this._videoDataIndex;
			var _videoIndex=this._videoIndex;
			
			let currentIndex = e.detail.current;
			if (currentIndex === _videoIndex&&!e.detail.realIndex) {
				return;
			}
			

			let isNext = false;
			if (currentIndex === 0 && _videoIndex === this.videoList.length - 1) {
				isNext = true;
			} else if (currentIndex === this.videoList.length - 1 && _videoIndex === 0) {
				isNext = false;
			} else if (currentIndex > _videoIndex) {
				isNext = true;
			}

			if (isNext) {
				_videoDataIndex++;
			} else {
				_videoDataIndex--;
			}
			
			_videoIndex = currentIndex >= this.videoList.length ? 0 : currentIndex;
			if (e.detail.realIndex) {
				_videoDataIndex = e.detail.realIndex;
				_videoIndex = 1;
			}
			
			if (_videoDataIndex < 0) {
				this.$cw.showError('无最新');
				return;
			} else if (_videoDataIndex >= this.videoDataList.length) {
				this.$cw.showError('看完了');
				this.openDj();
				return;
			}
			
			if (!this.videoDataList[_videoDataIndex].videoUrl) {
				this.$refs.buyPopup.open('bottom');
				return;
			}

			
			this.circular = (_videoDataIndex != 0);
			this._videoDataIndex=_videoDataIndex;
			this._videoIndex= _videoIndex;
			setTimeout(() => {
				this.updateVideo(false);
			}, 200);
		},
		updateVideo(isInit) {
			//let initIndex = this._videoDataIndex == 0 ? 1 : this._videoDataIndex;
			// let preVideo = this.videoList[0];
			// let currentVideo = this.videoList[1];
			// let nextVideo = this.videoList[2];
			// let preLst = this.videoDataList[(initIndex - 1)];
			let nextVideoIndex=this._videoIndex>=2?0:(this._videoIndex+1);
			let nextNextVideoIndex=nextVideoIndex>=2?0:(nextVideoIndex+1);
			
			let nextVideoDataIndex=this._videoDataIndex>=this.videoDataList.length-1?0:(this._videoDataIndex+1);
			let nextNextVideoDataIndex=nextVideoDataIndex>=this.videoDataList.length-1?0:(nextVideoDataIndex+1);
			
			let currentLst = this.videoDataList[this._videoDataIndex];
			let nextLst = this.videoDataList[nextVideoDataIndex];
			let nextNextLst = this.videoDataList[nextNextVideoDataIndex];
			this.$set(this.videoList[this._videoIndex], 'videoUrl', currentLst.videoUrl);
			this.$set(this.videoList[this._videoIndex], 'viedeoCollectionPosterUrl', currentLst.viedeoCollectionPosterUrl);
			this.$set(this.videoList[this._videoIndex], 'videoItem', currentLst);
			
			if(nextLst.videoUrl){
				this.$set(this.videoList[nextVideoIndex], 'videoUrl', nextLst.videoUrl);
				this.$set(this.videoList[nextVideoIndex], 'viedeoCollectionPosterUrl', nextLst.viedeoCollectionPosterUrl);
				this.$set(this.videoList[nextVideoIndex], 'videoItem', nextLst);
			}
			
			if(nextNextLst.videoUrl){
				this.$set(this.videoList[nextNextVideoIndex], 'videoUrl', nextNextLst.videoUrl);
				this.$set(this.videoList[nextNextVideoIndex], 'viedeoCollectionPosterUrl', nextNextLst.viedeoCollectionPosterUrl);
				this.$set(this.videoList[nextNextVideoIndex], 'videoItem', nextNextLst);
			}
			
			// if(this._videoIndex==2){
			// 	this.$set(nextVideo, 'videoUrl', currentLst.videoUrl);
			// 	this.$set(nextVideo, 'viedeoCollectionPosterUrl', currentLst.viedeoCollectionPosterUrl);
			// 	this.$set(nextVideo, 'videoItem', currentLst);
			// }else if(this._videoIndex==1){
			// 	this.$set(currentVideo, 'videoUrl', currentLst.videoUrl);
			// 	this.$set(currentVideo, 'viedeoCollectionPosterUrl', currentLst.viedeoCollectionPosterUrl);
			// 	this.$set(currentVideo, 'videoItem', currentLst);
			// }else if(this._videoIndex==0){
			// 	this.$set(preVideo, 'videoUrl', currentLst.videoUrl);
			// 	this.$set(preVideo, 'viedeoCollectionPosterUrl', currentLst.viedeoCollectionPosterUrl);
			// 	this.$set(preVideo, 'videoItem', currentLst);
			// }
			if(!isInit){
				this.playVideo(true);
			}

			// this.$set(nextVideo, 'videoUrl', nextLst.videoUrl);
			// this.$set(nextVideo, 'viedeoCollectionPosterUrl', nextLst.viedeoCollectionPosterUrl);
			// this.$set(nextVideo, 'videoItem', nextLst);

			// this.videoList[this._videoIndex]=Object.assign(this.$util.deepCopy(this.videoList[this._videoIndex]),this.$util.deepCopy(this.videoDataList[this._videoIndex]));
			// this.videoList[this.getNextIndex(isNext)]=Object.assign(this.$util.deepCopy(this.videoList[this.getNextIndex(isNext)]),this.$util.deepCopy(this.videoDataList[this._videoIndex]));
			// this.videoList[this._videoIndex]=Object.assign(this.videoList[this._videoIndex],this.videoDataList[this._videoDataIndex]);
			// this.videoList[this.getNextIndex(isNext)]=Object.assign(this.videoList[this.getNextIndex(isNext)],this.videoDataList[this.getNextDataIndex(isNext)]);
			// this.playVideo();
			// console.log("v:" + this._videoIndex + " d:" + this._videoDataIndex + "; next v:" + this.getNextIndex(
			// 	isNext) + " next d:" + this.getNextDataIndex(isNext));
		},
	},
	// 不要set的数据 统一用computed实现(能用computed 实现的 尽量用他实现 不要用data和method处理) 有返回值的不需要传参的method用computed实现 
	computed: {
		calDjDatas() {
			if (this.searchText) {
				return this.djDatas.filter(x => x.viedeoCollectionSort == this.searchText ||
					x.viedeoCollectionName.includes(this.searchText)
				);
			} else {
				return this.djDatas;
			}
		},
		item() {
			return this._.cloneDeep(this.inputItem);
		},
	},
	// 负责格式化数据 有返回值的需要传参的method 用filters实现
	filters: {
		// 多个参数filter 调用  {{day|weekDayFmt(getStudentListIn.month)}} filter filter后缀加上Fmt  vue3参考: http://knowledge.whcewei.com/CodeKnowledge/Detail-91D4B057-821A-4A0C-96E5-C0BC8CDDDC9C.aspx
		//weekDayFmt(day, yearMonth) {
		//    var weekDay = moment(yearMonth + "-" + day).day();
		//    var weekObj = { 1: "一", 2: "二", 3: "三", 4: "四", 5: "五", 6: "六", 0: "日" };
		//    return weekObj[weekDay];
		//},
	},
	// 负责数据变化后需要和接口交互
	watch: {
		"currentStatus": {
		   handler(val, oldval) {
		       if (val=='pause') {
				   document.querySelector(`#video${this._videoIndex} > div > div.uni-video-bar`).style.display='flex';
		       }else{
				    document.querySelector(`#video${this._videoIndex} > div > div.uni-video-bar`).style.display='none';
			   }
		   },
		},
		//"currentStore.storeId": {
		//    handler(val, oldval) {
		//        if (val) {
		//        }
		//    },
		//    deep: true,
		//    immediate: true
		//}
	},
}
export default mixin;